package com.foruo.algo.search;

/**
 * 二分查找
 * 前提： 有序数组
 * @author GaoYuan
 * @date 2018/10/25 下午8:45
 */
public class BinarySearchAlgo {

    private static int[] list = {1,2,3,4,5,6,7,8,9};

    public static int getIndex(int[] list, int target ,int start, int end){
        if(start > end || start < 0 || end >= list.length || target > list[end] || target < list[start]){
            System.out.println(end >= list.length);
            System.out.println(target > list[end]);
            System.out.println(start);
            System.out.println(target < list[start]);
            return -1;
        }
        int middleIndex = (end + start)/2;
        if(list[middleIndex] > target){
            return getIndex(list, target, start, list[middleIndex] - 1);
        }else if(list[middleIndex] < target){
            return getIndex(list, target, list[middleIndex], end);
        }else{
            return middleIndex;
        }
    }

    public static void main(String[] args){
        System.out.println(getIndex(list,  5, 0,list.length-1));
    }

}
